package 代码随想录.哈希表.两个数组的交集;

import java.util.ArrayList;
import java.util.HashSet;

/**lc:349. 两个数组的交集
 * link:https://leetcode-cn.com/problems/intersection-of-two-arrays/
 * @author ChenweiLin
 * @create 2021-12-15 10:09
 */
public class IntersectionOfTwoArrays {
    public static void main(String[] args) {
        int[] nums1 = new int[]{1,2,2,1};
        int[] nums2 = new int[]{2,2};

        int[] intersection = intersection(nums1, nums2);
        for (int i : intersection) {
            System.out.print(i+",");
        }
    }

    public static int[] intersection(int[] nums1, int[] nums2) {
        //两个HashSet求相同的
        HashSet<Integer> set1 = new HashSet<>();
        HashSet<Integer> set2 = new HashSet<>();
        for (int i : nums1) {
            set1.add(i);
        }

        for (int i : nums2) {
            set2.add(i);
        }

        ArrayList<Integer> list = new ArrayList<>();

        for (Integer integer : set1) {
            if (set2.contains(integer))
                list.add(integer);
        }

        int[] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            System.out.println(result[i] = list.get(i));
        }

        return result;
    }
}
